package com.cloudcentral.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * Create by WEI
 * 2023/7/10 17:39
 */
public class AESUtil {
  private final String algorithm = "AES";
  private final String secret;

  public AESUtil() {
    this("^AES_Secret_Key$");
  }

  public AESUtil(String secret) {
    this.secret = secret;
  }

  /**
   * AES加密
   *
   * @param data
   * @return
   * @throws Exception
   */
  public String encrypt(String data) throws Exception {
    SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), algorithm);
    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] encryptedBytes = cipher.doFinal(data.getBytes());
    return Base64.getEncoder().encodeToString(encryptedBytes);
  }

  /**
   * AES解密
   *
   * @param encryptedData
   * @return
   * @throws Exception
   */
  public String decrypt(String encryptedData) throws Exception {
    SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), algorithm);
    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
    return new String(decryptedBytes);
  }
}
